// 通过搜索框进入指定content页内容初始化
export default {
  data() {
    return {
      srcArrow: require("@/assets/arrow.jpg"),
    }
  },

    created() {
        // 通过搜索框跳转加载初始对话问题
        const searchName = localStorage.getItem('searchName');
        if(searchName){
            this.searchQuery = searchName
            this.submitSearch()
        }
    },
    methods: {
      parseJson(jsonStr){
        if (jsonStr.startsWith('{') && jsonStr.endsWith('}')) {
          try{
            return JSON.parse(jsonStr);
          } catch (error) {
            console.error('解析 jsonStr 数据时发生错误:', error);
          }
        }
      },
      // 新建对话
      splitData(streamBuffer){
        let messageList =[];
        let dataList = streamBuffer.split("data: ");
        for(let i=0;i<dataList.length;i++){
          const jsonData = this.parseJson(dataList[i].trim());
          if (!this.hasSetConversationId && jsonData.conversation_id) {
            this.conversationId = jsonData.conversation_id; // 更新 conversationId
            this.hasSetConversationId = true; // 设置标志为 true
          }
          if (jsonData.event === 'message') {
            if (!this.isTyping) {
              this.startBotMessage();
              this.isTyping = true;
            }
            let newText = jsonData.answer;
            this.isLoading = false;
            messageList.push(newText);
            // 触发打字效果逐字显示
            this.typewriterEffectNew(newText);
          }else if (jsonData.event === 'message_end') {
            this.finishBotMessage();
            this.isTyping = false;
            console.log('Message stream ended');
          } else if (jsonData.event === 'workflow_finished') {
            console.log('Workflow finished:', jsonData);
          } else if (jsonData.event === 'error') {
            this.isLoading = false;
            this.errorMessage = ''
            this.errorMessage = '网络异常'
            this.$refs.errorModal.show();  // 调用子组件的show方法显示弹框
            console.error('Stream error:', jsonData);
          } else {
            console.warn('Unhandled event type:', jsonData.event);
          }
        } 
     },
     typewriterEffectNew(text) {
      if (!this.isStreaming) return; // 检查是否停止打字效果
      const botMessage = this.conversation.find(msg => msg.type === 'bot' && !msg.completed);
      if (botMessage) {
        let messageText = botMessage.text || '';

        let parted = randomSplitString(text);
        for (let i = 0; i < parted.length; i++) {
          if (!this.isStreaming) break; // 停止显示效果
          messageText += parted[i];
          botMessage.text = messageText;
          // if(generateWeightedRandomNumber()>0){
          //   await this.delay(generateWeightedRandomNumber());
          // }
          this.scrollToBottom();
        }      
      }
    },
     scrollToBottomClick() {
      this.$nextTick(() => {
        const chatContainer = this.$refs.chatContainer;
        if (chatContainer) {
          const scrollHeight = chatContainer.scrollHeight;
          chatContainer.scrollTop = scrollHeight; // 滚动到底部
        }
      });
    },

    }
}
